package com.zhoufeng.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

import com.zhoufeng.common.Common;

public class ConnectionManager {
	
	private static Properties p = null;
	
	static {
		try {
			p = Common.loadPropertyFile("a_little_config.txt");
			// 注册驱动有如下方式：
			// 1.通过驱动管理器注册驱动，但会注册两次，并且会对类产生依赖。如果该类不存在那就报错了。
			// DriverManager.registerDriver(new com.mysql.jdbc.Driver());
			// 2.与3类似
			// System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");
			p = Common.loadPropertyFile("a_little_config.txt");
			Class.forName(p.getProperty("driverClass"));// 推荐使用方式
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() throws SQLException {
		//Class.forName(p.getProperty("driverClass"));
		Connection con = DriverManager.getConnection(p.getProperty("jdbcUrl"), p.getProperty("user"), p.getProperty("password"));
		return con;
	}
	public static Connection getConnection(boolean flag) throws SQLException {
		//Class.forName(p.getProperty("driverClass"));
		Connection con = DriverManager.getConnection(p.getProperty("jdbcUrl"), p.getProperty("user"), p.getProperty("password"));
		con.setAutoCommit(flag);
		return con;
	}

	public static void closeConnection(Connection con,PreparedStatement pstmt) {
		try {
			if (con != null && !con.isClosed()) {
				con.close();
			}
			if (pstmt != null && !pstmt.isClosed()) {
				pstmt.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
